<?php
class ModelSaleCustomerIp extends Model {
	public function getCustomerIps($filter) {
		$sql = "SELECT ip.*, c.email FROM @@customer_ip ip LEFT JOIN @@customer c
				 ON ip.customer_id = c.customer_id WHERE 1";
		
		if ($filter->get('filter_customer_id')) {
			$sql .= " AND ip.customer_id = " . $filter->get('filter_customer_id');
		}
		if ($filter->get('filter_email')) {
			$sql .= " AND c.email LIKE '%" . ES($filter->get('filter_email')) . "%'";
		}
		if ($filter->get('filter_ip')) {
			$sql .= " AND ip.ip = '" . ES($filter->get('filter_ip')) . "'";
		}
		if ($filter->get('filter_date_added')) {
			$sql .= " AND DATE(ip.date_added) = '" . ES($filter->get('filter_date_added')) . "'";
		}
		$sql .= $filter->sort('ip.customer_ip_id', 'DESC');
		$sql .= $filter->limit();
		
		$query = $this->db->query($sql);
		
		return $query->rows;
	}
	
	public function getTotalCustomerIps($filter) {
		$sql = "SELECT COUNT(*) FROM @@customer_ip WHERE 1";
		if ($filter->get('filter_customer_id')) {
			$sql .= " AND ip.customer_id = " . $filter->get('filter_customer_id');
		}
		if ($filter->get('filter_email')) {
			$sql .= " AND c.email LIKE '%" . ES($filter->get('filter_email')) . "%'";
		}
		if ($filter->get('filter_ip')) {
			$sql .= " AND ip.ip = '" . ES($filter->get('filter_ip')) . "'";
		}
		if ($filter->get('filter_date_added')) {
			$sql .= " AND DATE(ip.date_added) = '" . ES($filter->get('filter_date_added')) . "'";
		}
		
		return $this->db->queryOne($sql);
	}
	
	public function clearCustomerIps($older_than = 20) {
		return $this->db->runSql("DELETE FROM @@customer_ip WHERE DATE_SUB(CURDATE(),INTERVAL $older_than DAY) > date_added");
	}
}